package cn.qhfn.dao.impl;

import cn.qhfn.dao.BaseDao;
import cn.qhfn.dao.PetDao;
import cn.qhfn.entity.Pet;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class PetDaoImpl extends BaseDao implements PetDao {
    @Override
    public int addPet(Pet pet) {
        String sql = "insert into pet(petName,petBreed,petSex,birthday,description) values(?,?,?,?,?)";
        Object[] prs = {pet.getPetName(),pet.getPetBreed(),pet.getPetSex(),pet.getBirthday(),pet.getDescription()};
        return executeUpdate(sql, prs);
    }

    @Override
    public int deletePet(int id) {
        String sql = "delete from pet where id = ?";
        Object[] prs = {id};
        return executeUpdate(sql,prs);
    }

    @Override
    public int updatePet(Pet pet) {
        String sql = "update pet set petName=?,petBreed=?,petSex=?,birthday=?,description=? where id = ?";
        Object[] prs = {pet.getPetName(),pet.getPetBreed(),pet.getPetSex(),pet.getBirthday(),pet.getDescription(),pet.getPetId()};
        return executeUpdate(sql,prs);
    }

    @Override
    public Pet getPet(int id) {
        Pet pet = null;
        String sql = "select petId,petName,petBreed,petSex,birthday,description from pet where id = ?";
        Object[] prs = {id};
        ResultSet rs = executeQuery(sql,prs);
        try {
            while (rs.next()) {
                pet = new Pet();
                pet.setPetId(rs.getInt("petId"));
                pet.setPetName(rs.getString("petName"));
                pet.setPetBreed(rs.getInt("petBreed"));
                pet.setPetSex(rs.getInt("petSex"));
                pet.setBirthday(rs.getDate("birthday"));
                pet.setDescription(rs.getString("description"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeAll(conn,pstmt,rs);
        }
        return pet;
    }

    @Override
    public List<Pet> getPets() {
        List<Pet> pets = new ArrayList<Pet>();
        Pet pet = null;
        String sql = "select petId,petName,petBreed,petSex,birthday,description from pet";
        ResultSet rs = executeQuery(sql);
        try {
            while (rs.next()) {
                pet = new Pet();
                pet.setPetId(rs.getInt("petId"));
                pet.setPetName(rs.getString("petName"));
                pet.setPetBreed(rs.getInt("petBreed"));
                pet.setPetSex(rs.getInt("petSex"));
                pet.setBirthday(rs.getDate("birthday"));
                pet.setDescription(rs.getString("description"));
                pets.add(pet);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeAll(conn,pstmt,rs);
        }
        return pets;
    }
}
